#!/usr/bin/env python
# -*- coding:utf-8 -*-
import itertools
import collections
from django.forms import model_to_dict
from django.db.models import F
from rest_framework import status
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.filters import BaseFilterBackend
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView, ListAPIView, RetrieveAPIView
from rest_framework import exceptions
from django.db.models import Max, Count
from apps.api import models
from utils.auth import UserAuthentication, GeneralAuthentication
from utils.filters import ReachBottomFilter, PullDownRefreshFilter, MinCommentBackend


# ################################ 动态列表 & 发布动态 ################################

class CreateNewsTopicModelSerializer(serializers.Serializer):
    key = serializers.CharField()
    cos_path = serializers.CharField()


class CreateNewsModelSerializer(serializers.ModelSerializer):
    imageList = CreateNewsTopicModelSerializer(many=True)

    class Meta:
        model = models.News
        exclude = ['user', 'viewer_count', 'comment_count','favor_count']

    def create(self, validated_data):
        # 把用户提交的imageList切走，后端传入imageList，存放轮播图：
        # imageList：[{key:"文件名",cos_path:"文件网络地址"},{key:"文件名",cos_path:"文件网络地址"},]
        image_list = validated_data.pop('imageList')
        news_object = models.News.objects.create(**validated_data)
        # 批量创建图片到NewsDetail
        data_list = models.NewsDetail.objects.bulk_create(
            [models.NewsDetail(**info, news=news_object) for info in image_list]
        )
        news_object.imageList = data_list
        if news_object.topic:
            models.Topic.objects.filter(id=news_object.topic_id).update(count=F('count') + 1)

        return news_object


class ListNewsModelSerializer(serializers.ModelSerializer):
    topic = serializers.SerializerMethodField()
    user = serializers.SerializerMethodField()

    class Meta:
        model = models.News
        exclude = ['address', ]

    def get_topic(self, obj):
        if not obj.topic:
            return
        return model_to_dict(obj.topic, ['id', 'title'])

    def get_user(self, obj):
        return model_to_dict(obj.user, ['id', 'nickname', 'avatar'])


class NewsView(CreateAPIView, ListAPIView):
    """
    动态相关接口
        - 查看动态列表
        - 创建动态
    """
    queryset = models.News.objects.prefetch_related('user', 'topic').order_by("-id")

    filter_backends = [ReachBottomFilter, PullDownRefreshFilter]

    def get_authenticators(self):
        if self.request.method == 'POST':
            return [UserAuthentication(), ]
        return []

    def perform_create(self, serializer):
        new_object = serializer.save(user_id=self.request.user.id)
        return new_object

    def get_serializer_class(self):
        if self.request.method == 'POST':
            return CreateNewsModelSerializer
        if self.request.method == 'GET':
            return ListNewsModelSerializer


# ################################ 动态详细 ################################


class RetrieveNewsDetailModelSerializerSerializer(serializers.ModelSerializer):
    image_list = serializers.SerializerMethodField()
    topic = serializers.SerializerMethodField()
    user = serializers.SerializerMethodField()
    viewer = serializers.SerializerMethodField()
    comment = serializers.SerializerMethodField()
    create_date = serializers.DateTimeField(format='%Y-%m-%d')
    favor = serializers.SerializerMethodField()
    # 存放关注该动态的所有用户id
    # follow_users = serializers.SerializerMethodField()

    class Meta:
        model = models.News
        exclude = ['cover', ]

    def get_image_list(self, obj):
        return [model_to_dict(row, ['id', 'cos_path']) for row in obj.newsdetail_set.only('id', 'cos_path')]

    def get_topic(self, obj):
        if not obj.topic:
            return
        return model_to_dict(obj.topic, ['id', 'title'])

    def get_user(self, obj):
        context = model_to_dict(obj.user, ['id', 'nickname', 'avatar'])
        user_object = self.context['request'].user
        # 关注当前发布动态的用户id的列表
        follow_queryset_list = models.UserInfo.objects.filter(follow__id=obj.user_id)
        context['follow_user_list'] = [row.id for row in follow_queryset_list]
        if not user_object:
            return context
        # follow = user_object.follow.filter(id=obj.user_id).exists()
        # context['follow'] = follow
        return context

    def get_favor(self, obj):
        # user_object = self.context['request'].user
        # if not user_object:
        #     return False
        favor_queryset_list = models.NewsFavorRecord.objects.filter(news=obj)

        return  [row.user.id for row in favor_queryset_list]  # 直接列表形式存储点过赞的用户id
        # return models.NewsFavorRecord.objects.filter(news=obj, user=user_object).exists()

    def get_viewer(self, obj):
        queryset = models.ViewerRecord.objects.filter(news=obj).order_by('-id')
        view_object_list = queryset[0:10].values('user_id', 'user__avatar')

        mapping = {
            'user_id': 'id',
            'user__avatar': 'avatar'
        }
        context = {
            'count': queryset.count(),
            'result': [{mapping[key]: value for key, value in row.items()} for row in view_object_list]
        }
        return context

    def get_comment(self, obj):
        news_comment_queryset = models.CommentRecord.objects.filter(news=obj,isDelete=False)
        # 获取所有的评论数
        total_count = news_comment_queryset.count()

        mapping = {
            'id': 'id',
            'content': 'content',
            'create_date': 'create_date',
            'depth': 'depth',
            'user__nickname': "nickname",
            'user__avatar': "avatar",
            'user_id': "user__id",
            'reply_id': 'reply',
            'reply__user__nickname': "reply_nickname",
            'isDelete': "isDelete",
            'favor_count': "favor_count"
        }

        # 第一步： 获取前10条一级评论
        # 使用select_related()方法一次性的把CommentRecord关联的对象都查询出来放入对象中，
        # 再次查询时就不需要再连接数据库，节省了后面查询数据库的次数和时间。指定关键字参数可以只查询(join)指定的对象，节省资源
        all_first_queryset = news_comment_queryset.filter(depth=1).select_related('user', 'reply').order_by(
            '-id').values(*mapping.keys())
        first_depth_queryset = all_first_queryset[0:10]
        # 评论的id列表
        first_id_list = [item['id'] for item in first_depth_queryset]
        # 点赞过上述一级评论id的QuerySet对象列表
        first_comment_users_id_list = models.CommentFavorRecord.objects.filter(comment_id__in=first_id_list)
        first_depth_dict = collections.OrderedDict()
        for row in first_depth_queryset:

            row['create_date'] = row['create_date'].strftime('%Y-%m-%d %H:%M')
            row_dict = {mapping[key]: value for key, value in row.items()}
            # 点过该评论赞的用户id列表
            row_dict['first_comment_users_id_list'] = [item.user.id for item in first_comment_users_id_list if
                                                  row['id'] == item.comment.id]
            first_depth_dict[row['id']] = row_dict
        # 第二步：获取每个一级评论下的第一个二级评论的ID
        group_by_second_depth = news_comment_queryset.filter(depth=2, isDelete=False,reply__in=first_depth_dict.keys()).values(
            'reply_id').annotate(max_id=Max('id'))
        second_depth_id_list = [item['max_id'] for item in group_by_second_depth]

        # 第三步：根据第二步获取二级评论，并将二级评论添加到一级评论的child中。
        second_depth_queryset = news_comment_queryset.filter(depth=2, id__in=second_depth_id_list).select_related(
            'user', 'reply').order_by('id').values(*mapping.keys())
        # 点赞过上述二级评论id的用户id
        second_comment_users_id_list = models.CommentFavorRecord.objects.filter(
            comment_id__in=second_depth_id_list).values()
        # 增加一个获取每一个1级评论下的所有子评论个数，方便显示在获取更多评论按钮处显示
        # <QuerySet [{'root_id': 1, 'id__count': 6}, {'root_id': 8, 'id__count': 1}]>
        get_all = news_comment_queryset.filter(root_id__in=first_id_list).values(
            'root_id').annotate(Count("id"))
        # 1级评论下的所有相应子评论个数
        for child_comment in get_all:
            paraent_id = child_comment['root_id']
            # child_count随着评论的删除，相应变化
            first_depth_dict[paraent_id]['child_count'] = child_comment['id__count']
            # 子评论个数的初始值
            first_depth_dict[paraent_id]['init_child_count'] = child_comment['id__count']
        second_depth_dict = {}
        for row in second_depth_queryset:
            row['create_date'] = row['create_date'].strftime('%Y-%m-%d %H:%M')
            row_dict = {mapping[key]: value for key, value in row.items()}
            second_depth_dict[row['id']] = row_dict
            # 将点过id最大的二级评论赞的用户id列表second_comment_users_id_list存入child里
            row_dict['second_comment_users_id_list'] = [item['user_id'] for item in second_comment_users_id_list if
                                                    item['comment_id'] == row['id']]
            first_depth_dict[row_dict['reply']].setdefault('child', [])
            first_depth_dict[row_dict['reply']]['child'].append(row_dict)

        # 第四步：如果当前已赞过当前评论，则默认显示红色【已赞】，该方法有问题：
        # 如果用户未登录进入详情页，然后点赞提示登录，登录成功后返回详情页，小程序页面数据不会刷新，不会重新获取
        user_object = self.context['request'].user
        if user_object:
            news_id = itertools.chain(first_depth_dict.keys(), second_depth_dict.keys())
            user_comment_favor_queryset = models.CommentFavorRecord.objects.filter(user=user_object,
                                                                                   comment_id__in=news_id)
            for item in user_comment_favor_queryset:
                if item.comment_id in first_depth_dict:
                    first_depth_dict[item.comment_id]['favor'] = True
                if item.comment_id in second_depth_dict:
                    second_depth_dict[item.comment_id]['favor'] = True

        context = {
            # 所有评论数，包含一级评论和子评论
            'count': total_count,
            # *# 所有一级评论的总和
            'sum_first_comment' : len(all_first_queryset),
            'result': first_depth_dict.values()
        }
        return context


class NewsDetailView(RetrieveAPIView):
    """
    获取动态详细接口
    """
    queryset = models.News.objects
    serializer_class = RetrieveNewsDetailModelSerializerSerializer

    def get(self, request, *args, **kwargs):
        # 1. 获取详细信息
        response = self.retrieve(request, *args, **kwargs)

        # 2. 处理用户浏览记录，当前用户添加到记录中
        #    2.1 用户未登录，不记录
        #    2.2 用户登录，已记录则不再记录记录，未记录则添加到浏览记录中。
        if not request.user:
            return response
        news_object = self.get_object()
        if not news_object:
            return response

        viewer_queryset = models.ViewerRecord.objects.filter(news=news_object, user_id=request.user.id)
        if not viewer_queryset.exists():
            models.ViewerRecord.objects.create(news=news_object, user_id=request.user.id)
            models.News.objects.filter(id=news_object.id).update(viewer_count=F("viewer_count") + 1)

        return response


# ################################ 动态点赞 ################################
class NewsFavorSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.NewsFavorRecord
        exclude = ['user', ]


class NewsFavorView(APIView):
    serializer_class = NewsFavorSerializer
    authentication_classes = [UserAuthentication, ]

    def post(self, request, *args, **kwargs):
        """ 点赞和取消赞 """
        serializer = NewsFavorSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        news_object = serializer.validated_data.get('news')
        queryset = models.NewsFavorRecord.objects.filter(news=news_object, user=request.user)
        if queryset.exists():
            queryset.delete()
            models.News.objects.filter(id=news_object.id).update(favor_count=F("favor_count") - 1)
            return Response({}, status=status.HTTP_200_OK)
        serializer.save(user_id=request.user.id)
        models.News.objects.filter(id=news_object.id).update(favor_count=F("favor_count") + 1)

        return Response({}, status=status.HTTP_201_CREATED)


# ################################ 动态评论 & 所有评论 ################################


class CommentModelSerializer(serializers.ModelSerializer):
    create_date = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)
    nickname = serializers.CharField(source='user.nickname', read_only=True)
    user__id = serializers.CharField(source='user.id', read_only=True)
    avatar = serializers.CharField(source='user.avatar', read_only=True)
    reply_nickname = serializers.CharField(source='reply.user.nickname', read_only=True)
    favor = serializers.SerializerMethodField()
    second_comment_users_id_list = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = models.CommentRecord
        exclude = ["user"]

    def get_user(self, obj):
        return model_to_dict(obj.user, fields=['id', 'nickname', 'avatar'])

    def get_favor(self, obj):
        user_object = self.context['request'].user
        if not user_object:
            return False
        return models.CommentFavorRecord.objects.filter(user_id=user_object.id, comment=obj).exists()
    # 子评论的点赞记录的用户id列表
    def get_second_comment_users_id_list(self, obj):
        favor_queryset = models.CommentFavorRecord.objects.filter(comment_id=obj.id)
        favor_queryset_list = favor_queryset.order_by('-id')
        return [row.user.id for row in favor_queryset_list]


class ChildCommentFilter(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        root_comment_id = request.query_params.get('root_id')
        if not root_comment_id:
            return queryset.none()
        # 获取所有子评论，按照id倒序排
        return queryset.filter(root_id=root_comment_id).order_by('-id')

# 评论
class CommentView(CreateAPIView, ListAPIView):
    serializer_class = CommentModelSerializer
    queryset = models.CommentRecord.objects

    filter_backends = [ChildCommentFilter, ]

    def get_authenticators(self):
        if self.request.method == 'POST':
            return [UserAuthentication(), ]
        return [GeneralAuthentication(), ]

    def perform_create(self, serializer):
        serializer.save(user_id=self.request.user.id)
        news_object = serializer.validated_data.get('news')
        models.News.objects.filter(id=news_object.id).update(comment_count=F("comment_count") + 1)


# ################################ 评论点赞 ################################
class FavorSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.CommentFavorRecord
        exclude = ['user', ]


class CommentFavorView(APIView):
    serializer_class = FavorSerializer
    authentication_classes = [UserAuthentication, ]

    def post(self, request, *args, **kwargs):
        """ 点赞和取消赞 """
        serializer = FavorSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        comment_object = serializer.validated_data.get('comment')
        queryset = models.CommentFavorRecord.objects.filter(comment=comment_object, user_id=request.user.id)
        # 已存在，删除赞
        if queryset.exists():
            queryset.delete()
            models.CommentRecord.objects.filter(id=comment_object.id).update(favor_count=F("favor_count") - 1)
            return Response({}, status=status.HTTP_200_OK)
        # 不存在，创建赞
        serializer.save(user_id=request.user.id)
        models.CommentRecord.objects.filter(id=comment_object.id).update(favor_count=F("favor_count") + 1)
        return Response(serializer.data, status=status.HTTP_201_CREATED)


# ################################ 动态关注 ################################

class FollowSerializer(serializers.Serializer):
    user = serializers.IntegerField(label='要关注的用户ID')

    def validate_user(self, value):
        exists = models.UserInfo.objects.filter(id=value).exists()
        if not exists:
            raise exceptions.ValidationError('用户不存在')
        return value


class FollowView(APIView):
    serializers = [UserAuthentication, ]
    # 可以建立一个关注列表，当前登录用户关注了哪些用户id
    def post(self, request, *args, **kwargs):
        """ 关注和取消关注：已关注则取消，未关注则关注"""
        ser = FollowSerializer(data=request.data)
        ser.is_valid(raise_exception=True)
        # 被关注者的id
        target_user_id = ser.validated_data.get('user')
        # 关注者的用户对象，也就是登录的用户
        current_user_object = request.user
        exists = current_user_object.follow.filter(id=target_user_id).exists()
        if exists:
            # 已关注，则取消关注
            current_user_object.follow.remove(target_user_id)
            models.UserInfo.objects.filter(id=target_user_id).update(fans_count=F('fans_count') - 1)
            return Response({}, status=status.HTTP_200_OK)

        # 未关注，则关注
        current_user_object.follow.add(target_user_id)
        models.UserInfo.objects.filter(id=target_user_id).update(fans_count=F('fans_count') + 1)
        return Response({}, status=status.HTTP_201_CREATED)


# ---------------------------获取浏览记录用户功能------------------------------------------
# http://127.0.0.1:8000/api/viewerrecord/?newsId=1&&minId=13
class ViewerRecordModelSerializer(serializers.ModelSerializer):
    user = serializers.SerializerMethodField()

    class Meta:
        model = models.ViewerRecord
        fields = ['user', 'news_id','id']

    def get_user(self, obj):
        context = model_to_dict(obj.user, ['id', 'nickname', 'avatar'])
        # 登录者对象
        # user_object = self.context
        # 用户发布动态的数量
        news_quertset = models.News.objects.filter(user_id=obj.user_id)
        exists = news_quertset.exists()
        context['news_count'] = 0
        if exists:
            context['news_count'] = news_quertset.count()
        # 关注当前发布动态的用户id的列表
        follow_queryset_list = models.UserInfo.objects.filter(follow__id=obj.user_id).order_by('-id')
        context['follow_user_list'] = [row.id for row in follow_queryset_list]
        # if not user_object:
        #     return context
        # follow = user_object.follow.filter(id=obj.user_id).exists()
        # context['follow'] = follow
        return context
        # return model_to_dict(instance=obj.user, fields=['id', 'nickname', 'avatar'])
# 此功能为小程序用户中心点击关注返回的关注用户列表数据
class FollowModelSerializer(serializers.ModelSerializer):
    user = serializers.SerializerMethodField()
    class Meta:
        model = models.UserInfo
        fields = ['user']
    def get_user(self, obj):
        context = model_to_dict(obj, ['id', 'nickname', 'avatar'])
        # 用户发布动态的数量,obj.id被关注者的id
        news_quertset = models.News.objects.filter(user_id=obj.id)
        exists = news_quertset.exists()
        context['news_count'] = 0
        if exists:
            context['news_count'] = news_quertset.count()
        # 关注当前发布动态的用户id的列表
        follow_queryset_list = models.UserInfo.objects.filter(follow__id=obj.id).order_by('-id')
        context['follow_user_list'] = [row.id for row in follow_queryset_list]

        return context
class ViewerRecordView(APIView):
    '''
    获取浏览记录和关注用户功能
    '''
    def get_authenticators(self):
        if self.request.GET['newsId'] == '-1':
            return [UserAuthentication(), ]
    def get(self, request, *args, **kwargs):
        newsId = request.query_params.get('newsId', '')
        maxId = request.query_params.get('maxId')
        minId = request.query_params.get('minId')
        # 如果是-1代表从个人中心关注页面跳转的，需要返回登录者关注用户的信息，不支持下拉上刷
        if newsId == "-1":
            queryset = models.UserInfo.objects.filter(follow__id=request.user.id)
            # queryset = queryset_all
            # if maxId:
            #     queryset = queryset_all.filter(id__gt=maxId)[0:10]
            #     # queryset = queryset_all.filter(user_id__gt=maxId)[0:10]
            # if minId:
            #     queryset = queryset_all.filter(id__lt=minId)[0:10]
            ser = FollowModelSerializer(instance=queryset, many=True, context=request.user)
            return Response(ser.data, status=status.HTTP_200_OK)
        elif newsId:
            queryset_all = models.ViewerRecord.objects.filter(news_id=newsId).order_by('-id')
            # queryset_all = models.ViewerRecord.objects.filter(news_id=newsId).order_by('-user_id')
            queryset = queryset_all[0:10]
            if maxId:
                queryset = queryset_all.filter(id__gt=maxId)[0:10]
                # queryset = queryset_all.filter(user_id__gt=maxId)[0:10]
            if minId:
                queryset = queryset_all.filter(id__lt=minId)[0:10]
                # queryset = queryset_all.filter(user_id__lt=minId)[0:10]
        else:
            queryset = models.ViewerRecord.objects.all()
        ser = ViewerRecordModelSerializer(instance=queryset, many=True,context=request.user)
        return Response(ser.data, status=status.HTTP_200_OK)



# ---------------------------获取更多动态评论功能------------------------------------------
# http://127.0.0.1:8000/api/getmorecomment/?newsId=1
class GetMoreCommentViewModelSerializer(serializers.ModelSerializer):
    comment = serializers.SerializerMethodField()
    create_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M")
    class Meta:
        model = models.News
        fields = '__all__'
        # exclude = ['news', 'reply', 'user', 'root']

    def get_comment(self, obj):
        news_comment_queryset = models.CommentRecord.objects.filter(news=obj, isDelete=False)
        # 获取所有的评论数
        total_count = news_comment_queryset.count()

        mapping = {
            'id': 'id',
            'content': 'content',
            'create_date': 'create_date',
            'depth': 'depth',
            'user__nickname': "nickname",
            'user__avatar': "avatar",
            'user_id': "user__id",
            'reply_id': 'reply',
            'reply__user__nickname': "reply_nickname",
            'isDelete': "isDelete",
            'favor_count': "favor_count"
        }

        # 第一步： 获取前10条一级评论
        # 使用select_related()方法一次性的把CommentRecord关联的对象都查询出来放入对象中，
        # 再次查询时就不需要再连接数据库，节省了后面查询数据库的次数和时间。指定关键字参数可以只查询(join)指定的对象，节省资源
        all_first_queryset = news_comment_queryset.filter(depth=1).select_related('user', 'reply').order_by(
            '-id').values(*mapping.keys())
        first_depth_queryset = all_first_queryset
        # 评论的id列表
        first_id_list = [item['id'] for item in first_depth_queryset]
        # 点赞过上述一级评论id的QuerySet对象列表
        first_comment_users_id_list = models.CommentFavorRecord.objects.filter(comment_id__in=first_id_list)
        first_depth_dict = collections.OrderedDict()
        for row in first_depth_queryset:
            row['create_date'] = row['create_date'].strftime('%Y-%m-%d %H:%M')
            row_dict = {mapping[key]: value for key, value in row.items()}
            # 点过该评论赞的用户id列表
            row_dict['first_comment_users_id_list'] = [item.user.id for item in first_comment_users_id_list if
                                                       row['id'] == item.comment.id]
            first_depth_dict[row['id']] = row_dict
        # 第二步：获取每个一级评论下的第一个二级评论的ID
        group_by_second_depth = news_comment_queryset.filter(depth=2, isDelete=False,
                                                             reply__in=first_depth_dict.keys()).values(
            'reply_id').annotate(max_id=Max('id'))
        second_depth_id_list = [item['max_id'] for item in group_by_second_depth]

        # 第三步：根据第二步获取二级评论，并将二级评论添加到一级评论的child中。
        second_depth_queryset = news_comment_queryset.filter(depth=2, id__in=second_depth_id_list).select_related(
            'user', 'reply').order_by('id').values(*mapping.keys())
        # 点赞过上述二级评论id的用户id
        second_comment_users_id_list = models.CommentFavorRecord.objects.filter(
            comment_id__in=second_depth_id_list).values()
        # 增加一个获取每一个1级评论下的所有子评论个数，方便显示在获取更多评论按钮处显示
        # <QuerySet [{'root_id': 1, 'id__count': 6}, {'root_id': 8, 'id__count': 1}]>
        get_all = news_comment_queryset.filter(root_id__in=first_id_list).values(
            'root_id').annotate(Count("id"))
        # 1级评论下的所有相应子评论个数
        for child_comment in get_all:
            paraent_id = child_comment['root_id']
            # child_count随着评论的删除，相应变化
            first_depth_dict[paraent_id]['child_count'] = child_comment['id__count']
            # 子评论个数的初始值
            first_depth_dict[paraent_id]['init_child_count'] = child_comment['id__count']
        second_depth_dict = {}
        for row in second_depth_queryset:
            row['create_date'] = row['create_date'].strftime('%Y-%m-%d %H:%M')
            row_dict = {mapping[key]: value for key, value in row.items()}
            second_depth_dict[row['id']] = row_dict
            # 将点过id最大的二级评论赞的用户id列表second_comment_users_id_list存入child里
            row_dict['second_comment_users_id_list'] = [item['user_id'] for item in second_comment_users_id_list if
                                                        item['comment_id'] == row['id']]
            first_depth_dict[row_dict['reply']].setdefault('child', [])
            first_depth_dict[row_dict['reply']]['child'].append(row_dict)

        # 第四步：如果当前已赞过当前评论，则默认显示红色【已赞】，该方法有问题：
        # 如果用户未登录进入详情页，然后点赞提示登录，登录成功后返回详情页，小程序页面数据不会刷新，不会重新获取
        user_object = self.context['request'].user
        if user_object:
            news_id = itertools.chain(first_depth_dict.keys(), second_depth_dict.keys())
            user_comment_favor_queryset = models.CommentFavorRecord.objects.filter(user=user_object,
                                                                                   comment_id__in=news_id)
            for item in user_comment_favor_queryset:
                if item.comment_id in first_depth_dict:
                    first_depth_dict[item.comment_id]['favor'] = True
                if item.comment_id in second_depth_dict:
                    second_depth_dict[item.comment_id]['favor'] = True

        context = {
            # 所有评论数，包含一级评论和子评论
            'count': total_count,
            # *# 所有一级评论的总和
            'sum_first_comment': len(all_first_queryset),
            'result': first_depth_dict.values()
        }
        return context


class GetMoreCommentView(ListAPIView):
    '''
    获取更多动态评论功能，一次性全部获取，理想状态是每次只获取10条
    '''
    queryset = models.News.objects
    serializer_class = GetMoreCommentViewModelSerializer
    filter_backends = [MinCommentBackend]

# ---------------------------删除子评论功能--------------------------------------
class DelCommentRecordModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.CommentRecord
        fields = ['id','depth']
        # fields = '__all__'

class DelCommentRecordView(APIView):
    authentication_classes = [UserAuthentication, ]
    def post(self, request, *args, **kwargs):
        # 进行数据校验
        ser = DelCommentRecordModelSerializer(data=request.data)
        if not ser.is_valid():
            return Response({},status=status.HTTP_400_BAD_REQUEST)
        depth = ser.validated_data.get('depth')
        queryset = models.CommentRecord.objects.filter(id=request.data['comment_id'], user=request.user)
        exists = queryset.exists()
        if exists:
            if depth== 1:
                print("删除一级评论")
                # 其下子评论个数
                childcount = int(request.data['childcount'])
                queryset.update(isDelete=True)
                models.CommentRecord.objects.filter(root_id=request.data['comment_id']).update(isDelete=True)
                models.News.objects.filter(id=request.data['news']).update(comment_count=F('comment_count') - 1 - childcount)
            else:
                print("删除")
                queryset.update(isDelete=True)
                models.News.objects.filter(id=request.data['news']).update(comment_count=F('comment_count') - 1)


            return Response({}, status=status.HTTP_200_OK)
        else:
            return Response({},status=status.HTTP_400_BAD_REQUEST)
